import { LoginType } from '@/pages/Login/services'
import { notification } from 'antd'
import { history } from '@umijs/max'

/**
 * 请求没选配置项
 */
interface Option {
  method?: 'GET' | 'POST' // 默认 POST
  token?: string
  data?: Record<string, any> // 默认空对象 {}
  header?: Record<string, string> // 请求头
  errHandle?: boolean // 是否走统一处理错误逻辑 默认 true
}

/**
 * 服务器统一返回数据格式
 */
interface Result<T> {
  code: string;
  data: T;
  text: string;
  totalCount?: number;
}

/**
 * 错误信息映射
 */
const errorMsgMap: Record<number | string, string> = {
  400: '参数不正确',
  403: '没有访问权限',
  404: '请求的资源不存在',
  500: '服务器错误',
}

/**
 * 处理 http 返回结果，返回 json 对象
 */
async function dealResponse<T>(res: Response): Promise<Result<T>> {
  if (res.ok) return res.json()
  notification.error({
    message: res.status,
    description: errorMsgMap[res.status],
  })
  return Promise.reject()
}

/**
 * 统一业务错误处理逻辑
 */
async function errHandle<T>(res: Result<T>, deal: boolean = true): Promise<Result<T>> {
  if (!deal) return res
  const { code, text } = res
  if (code === '402' || code === '403') {
    const userType = sessionStorage.userType
    if (userType === String(LoginType.大客户登录)) {
      localStorage.removeItem('Authorization2')
    } else {
      localStorage.removeItem('Authorization')
    }
    let originHref: string
    if (window.location.href.includes('redirect=')) {
      originHref = window.location.href.split('redirect=').at(-1) || '/'
    } else {
      originHref = encodeURIComponent(window.location.href)
    }
    if (userType === String(LoginType.大客户登录)) {
      history.replace(`/vipLogin?redirect=${originHref}`)
    } else {
      history.replace(`/login?redirect=${originHref}`)
    }
    return res
  }
  if (code === '408') {
    history.replace('/408')
    return res
  }
  if (code === '200') return res
  notification.error({
    message: '错误',
    description: text,
  })
  return Promise.reject()
}

async function request<T = unknown>(url: string, option?: Option): Promise<Result<T>> {
  const method = option?.method || 'POST'

  let finalUrl = `${BASE_HOST}${url}`

  const defaultData: Record<string, any> = {
    source: 'pc',
    ...option?.data,
  }

  console.log(defaultData)

  if (option?.method === 'GET') {
    let params = ''
    Object.keys(defaultData).forEach(key => {
      params = `${params}${key}=${defaultData[key]}&`
    })
    finalUrl = `${finalUrl}?${params}`
  }

  const _isFile = option?.data instanceof FormData
  const _headers: Record<string, string> = {
    Authorization: option?.token || localStorage.Authorization,
    ...option?.header,
  }
  if (!_isFile) {
    _headers['Content-Type'] = 'application/json;charset=utf-8'
  }

  return fetch(
    finalUrl,
    {
      method,
      headers: _headers,
      body: method === 'POST' ? (_isFile ? option.data : JSON.stringify(defaultData)) : undefined,
      mode: 'cors',
      credentials: 'include',
    }
  )
  .then(res => dealResponse<T>(res))
  .then(res => errHandle<T>(res, option?.errHandle))
}

export default request
